//
//  TRProductDetailViewController.m
//  WeiMiLan
//
//  Created by anan on 14/11/20.
//  Copyright (c) 2014年 Mac. All rights reserved.
//

#import "TRProductDetailViewController.h"
#import "TREmptyViewController.h"
//#import "CXAlertView.h"
#import "DLAVAlertView.h"


@interface TRProductDetailViewController ()<DLAVAlertViewDelegate>

{
    int historyY;
    CGRect tableViewFrame;
}
@property (nonatomic, strong) UIWebView *webView;
@property (weak, nonatomic) DLAVAlertView *alertView;
@property (nonatomic, strong) NSMutableArray *arrayList;

@property (assign, nonatomic) NSUInteger avatorTag;

@property (weak, nonatomic) IBOutlet UIButton *favBtn;



@end

@implementation TRProductDetailViewController

- (UIWebView *)webView {
    if (_webView == nil) {
        _webView = [[UIWebView alloc]init];
    }
    return _webView;
}

- (NSMutableArray *)arrayList {
    if (_arrayList == nil) {
        _arrayList = [NSMutableArray array];
    }
    return _arrayList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    [self initNavigation];
  
    self.info=[[NSUserDefaults standardUserDefaults]objectForKey:@"DetailInfo"];
    NSDictionary *dic=[[NSDictionary alloc]init];
    dic=self.info;
    // 1.注册
    UINib *nib1 = [UINib nibWithNibName:@"TRCommentTableViewCell" bundle:nil];
    [self.tableView registerNib:nib1 forCellReuseIdentifier:@"TRCommentTableViewCell"];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.scrollsToTop = YES;
    
    
    self.productDetailHeaderView = [[[NSBundle mainBundle] loadNibNamed:@"TRProductDetailHeaderView" owner:self options:nil] lastObject];

    [self loadProductDetail];
    
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    self.imageViewUserHead.layer.masksToBounds = YES;
    self.imageViewUserHead.layer.cornerRadius = 18; //设置图片圆角的尺度
    [self.imageViewUserHead sd_setImageWithURL:[NSURL URLWithString:userInfo[@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_public"]];
    
    self.productDetailHeaderView.scrollView.scrollsToTop = NO;
    self.productDetailHeaderView.scrollViewUsers.scrollsToTop = NO;
    
   // self.productDetailHeaderView.height = 900;
    self.tableView.tableHeaderView = self.productDetailHeaderView;
  //  self.tableView.tableHeaderView.height =[self.productDetailHeaderView getHeight];
    self.library = [[ALAssetsLibrary alloc] init];
    self.textFieldContent.delegate = self;
    
    [self updateFavButton];
    if ([QLPropertyUtils getBoolByKey:@"guide_share" defaultValue:NO]==NO) {
        self.viewGuide.hidden = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(guideTap:)];
        [self.viewGuide addGestureRecognizer:tap];
    }
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(prasieActionData:) name:@"kPrasieAction" object:nil];
    
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 37, 0);
  
    
    [self addHeader];
    [self addFooter];
}

- (void)getReply {
    NSString *userId = [NSStandardUserDefaults objectForKey:@"USER_ID"];
    NSDictionary *parameters = @{@"userId" : userId,
                                 @"type" : @"10002",
                                 @"productId":self.productTypeId,
                                 @"pageNum" : @1
                                 };

    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [SVProgressHUD show];
    //int productId = [self.info ql_intForKey:@"ID"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Comment" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
       
        
        NSDictionary *dic = responseObject;
        if ([dic ql_intForKey:@"code"]==0000) {
            [self.arrayList addObject:dic[@"COMMENT_RSP"][@"COMMENTS"]];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    }];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
   //
    NSLog(@"%@==========",NSStringFromCGRect(self.tableView.frame));
}
- (void)prasieActionData:(NSNotification *)noti {
    
    [self loadData:1];
}
- (void)loadData:(int)num
{
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:QLIntToNumber(num) forKey:@"PAGE_NUM"];
    [dic ql_setInterge:[userInfo ql_intForKey:@"ID"] forKey:@"userId"];
    [dic setObject:self.productTypeId forKey:@"productId"];
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Comment?type=10002" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            if (num==1) {
                //第一页
                if ([responseObject[@"COMMENT_RSP"][@"COMMENTS"] isKindOfClass:[NSDictionary class]]) {
                    [self.contents addObject:responseObject[@"COMMENT_RSP"][@"COMMENTS"]];
                    NSLog(@"self.contents11=%@",self.contents);
                }else{
                    self.contents = [NSMutableArray arrayWithArray:responseObject[@"COMMENT_RSP"][@"COMMENTS"]];
                    NSLog(@"self.contents22=%@",self.contents);
                }
            }else{
                [self.contents addObjectsFromArray:responseObject[@"COMMENT_RSP"][@"COMMENTS"]];
                NSLog(@"self.contents33=%@",self.contents);
            }
            
            NSDictionary *pageInfo = responseObject[@"PAGE_INFO"];
            self.nextPage = [pageInfo ql_intForKey:@"NEXT"];
            self.currentPage = [pageInfo ql_intForKey:@"NUMBER"];
            if (self.nextPage>self.currentPage) {
                refreshFooterView.isend = NO;
            }else{
                refreshFooterView.isend = YES;
            }
            
            [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:2.0f];
        }
      //  NSLog(@"%@",[NSString stringWithFormat:@"%@",responseObject[@"PAGE_INFO"][@"COUNT"]]);
        [[NSNotificationCenter defaultCenter]postNotificationName:@"kCommetnCountChanged" object:nil userInfo:@{@"count": [NSString stringWithFormat:@"%@",responseObject[@"PAGE_INFO"][@"COUNT"]]}];
        NSMutableArray *arrAvator = [NSMutableArray array];
        if (self.contents.count>0) {

            NSUInteger x = 6;
            for (NSDictionary *dic in self.contents) {
               
                NSMutableDictionary *dictAvator = [NSMutableDictionary dictionary];
                dictAvator[@"userID"] = dic[@"AUTHOR_ID"];
                dictAvator[@"userAvator"] = dic[@"AUTHOR_HEAD_PIC"];
                
                [arrAvator addObject:dictAvator];
                if (dic == self.contents.lastObject) {
                    NSLog(@"--------%@",arrAvator);
                    arrAvator = [NSMutableArray arrayWithArray:[self arrayWithMemberIsOnly:arrAvator]];
                    NSLog(@"--------+++++++++--------%@",arrAvator);
                  
             
                    for (NSDictionary *userDict in arrAvator) {
                         CGRect r = CGRectMake(x, 6, 36, 36);
                        x = x+36+5;
                        if (x > [UIScreen mainScreen].bounds.size.width) {
                            return ;
                        }
                        
                        NSLog(@"=============%@",userDict);
                        UIImageView *imageView = [[UIImageView alloc] initWithFrame:r];
                        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                        button.frame = r;
                        button.tag = [userDict[@"userID"] integerValue];
                        [button addTarget:self action:@selector(buttonUserDetailAction:) forControlEvents:UIControlEventTouchUpInside];
                        imageView.layer.masksToBounds = YES;
                        imageView.layer.cornerRadius = 18; //设置图片圆角的尺度
                        [imageView setImageWithURL:[NSURL URLWithString:userDict[@"userAvator"]] placeholderImage:[UIImage imageNamed:@"nodata_userheader"]];
                  
                        [self.productDetailHeaderView.scrollViewUsers addSubview:imageView];
                        [self.productDetailHeaderView.scrollViewUsers addSubview:button];
                    }
                }
                 
            }
            
        }
       
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
        [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:2.0f];
    }];
}
- (NSArray *)arrayWithMemberIsOnly:(NSArray *)array
{
    if (array.count == 0) {
        return nil;
    }
    if (array.count == 1) {
        return array;
    }
    NSMutableArray *useridArray = [[NSMutableArray alloc] init];
    NSMutableArray *useravatorArray = [[NSMutableArray alloc] init];
//    for (unsigned i = 0; i < [array count]; i++) {
////        if ([categoryArray containsObject:[array objectAtIndex:i]] == NO) {
////            [categoryArray addObject:[array objectAtIndex:i]];
////        }
//
////        NSDictionary *dict = array[i];
////        NSDictionary *dictnext = array[i+1];
////        NSLog(@"%ld----%ld",[dict[@"userID"] integerValue],[dictnext[@"userID"]integerValue]);
////        if ([dict[@"userID"] integerValue] == [dictnext[@"userID"] integerValue]) {
////           // [categoryArray addObject:dict];
////            
////            
////            
////         //   [categoryArray removeObject:dict];
////            
////        }
////        else {
////            [categoryArray addObject:dictnext];
////        }
//    }
    NSMutableArray *userInfo = [NSMutableArray array];
    
    for (unsigned i = 0; i < [array count]; i++) {
    if ([useravatorArray containsObject:[array objectAtIndex:i][@"userAvator"]] == NO) {
            [useravatorArray addObject:[array objectAtIndex:i][@"userAvator"]];
        }
    }
    for (unsigned i = 0; i < [array count]; i++) {
        if ([useridArray containsObject:[array objectAtIndex:i][@"userID"]] == NO) {
            [useridArray addObject:[array objectAtIndex:i][@"userID"]];
        }
    }
    for (NSUInteger i = 0; i < useridArray.count; i++) {
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"userID"] = useridArray[i];
        dict[@"userAvator"] = useravatorArray[i];
        [userInfo addObject:dict];
    }
   // userAvator
    return userInfo;
}
- (void)guideTap:(id)sender
{
    self.viewGuide.hidden = YES;
    [QLPropertyUtils putBoolByKey:@"guide_share" value:YES];
}

- (void) disableScrollsToTopPropertyOnAllSubviewsOf:(UIView *)view {
    for (UIView *subview in view.subviews) {
        if ([subview isKindOfClass:[UIScrollView class]]) {
            ((UIScrollView *)subview).scrollsToTop = NO;
        }
        [self disableScrollsToTopPropertyOnAllSubviewsOf:subview];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UITapGestureRecognizer *tapGr = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(viewTapped:)];
    tapGr.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:tapGr];
    [self registerForKeyboardNotifications];

    if (self.rectViewComment.size.width==0) {
        self.rectViewComment = self.viewComment.frame;
    }
    
    NSArray * weixinBtn = [[NSBundle mainBundle]loadNibNamed:@"TRWeixin" owner:self options:nil];
    self.weixinView = [weixinBtn lastObject];

    self.productDetailHeaderView.viewController = self;
    [self disableScrollsToTopPropertyOnAllSubviewsOf:self.tableView];
    
    [self updateFavButton];
}

-(void)viewTapped:(UITapGestureRecognizer*)tapGr{
    [self.textFieldContent resignFirstResponder];
}

- (void)registerForKeyboardNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHidden:) name:UIKeyboardDidHideNotification object:nil];
}

- (void)keyboardWasShown:(NSNotification *) notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGRect r = self.rectViewComment;
    r.origin.y = self.rectViewComment.origin.y - keyboardSize.height;
    self.viewComment.frame = r;
}

- (void)keyboardWasHidden:(NSNotification *) notif{
    self.viewComment.frame = self.rectViewComment;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //[[QLRecordPlayer shareInstance] stop];
}

- (void)loadProductDetail
{
    ApplicationDelegate.shareImage = nil;
    [QLMaskUtil showMaskLoadingWithView:self.tableView];
    [ApplicationDelegate.webAPI getWebAPIWithParams:@{@"type":SERVICE_CODE_PRODUCT_PREVIEW,PRODUCT_TYPE_ID:self.productTypeId?self.productTypeId:@""} andMethodNode:NODE_PRODUCT completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        [QLMaskUtil hideLoadingMaskWithView:self.tableView];
        if (state==1) {
            ApplicationDelegate.shareContent=responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"][@"DESCRIPTION"];
            self.productInfo = responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"];
            if ([self.productInfo ql_hasObjectForKey:@"TONE_URL"]) {
                self.viewPlay.hidden = NO;
                if ([self.productInfo ql_hasObjectForKey:@"TONE_TIME"]) {
                    if ([[self.productInfo ql_stringForKey:@"TONE_TIME"] isEqualToString:@"null"]) {
                        self.labelTLong.text = @"0";
                    }else {
                        self.labelTLong.text = [NSString stringWithFormat:@"%@'",[self.productInfo ql_stringForKey:@"TONE_TIME"]];
                    }
                 
                }
            }else{
                self.viewPlay.hidden = YES;
            }
            NSArray *imgs = responseObject[@"PRODUCT_RSP"][@"PRODUCT"];
            if (imgs&&imgs.count>0) {
                NSDictionary *dic = [imgs firstObject];
                [[[SDWebImageManager sharedManager] imageDownloader]downloadImageWithURL:[NSURL URLWithString:dic[@"PIC_URL"]] options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                    
                } completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
                    ApplicationDelegate.shareImage = image;
                }];
            }
            
            ApplicationDelegate.shareTitle=responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"][@"NAME"];
            ApplicationDelegate.shareURL=responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"][@"SHARE_URL"];
            
            NSString* code = responseObject[@"MESSAGE_INFO"][@"CODE"];
            NSString* message=responseObject[@"MESSAGE_INFO"][@"MESSAGE"];
            
            if ([code isEqualToString:@"0000"]) {
                NSArray *imgs = responseObject[@"PRODUCT_RSP"][@"PRODUCT"];
                NSDictionary *dic =responseObject[@"PRODUCT_RSP"][@"PRODUCT_INFO"];
                self.productDetailHeaderView.userInfo = responseObject[@"PRODUCT_RSP"][@"USER_INFO"];
                [self.productDetailHeaderView setInfo:dic andImgs:imgs businnessTag:responseObject[@"PRODUCT_RSP"][@"BUSINESS_TAG"]];
                self.tableView.tableHeaderView = self.productDetailHeaderView;
                [self setupDelete];
                
           //     NSDictionary *ui = self.productDetailHeaderView.userInfo;
//                if ([QLPublic isWXAppInstalled]){
//                    self.buttonWechar.enabled = [ui ql_hasObjectForKey:@"WECHAT"];
//                }
//                if ([TencentOAuth iphoneQQInstalled]) {
//                    self.buttonQQ.enabled = [ui ql_hasObjectForKey:@"QQ"];
//                }
//                
//                self.buttonPhone.enabled = [ui ql_hasObjectForKey:@"PHONE"];

            }else{
                [SVProgressHUD showImage:nil status:message];
            }
        }
        [self performSelector:@selector(doneWithView:) withObject:nil afterDelay:0.2f];
    }];
}

- (void)loadFavs:(int)startX
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:QLIntToNumber(1) forKey:@"PAGE_NUM"];
    [dic setObject:self.productTypeId forKey:@"ID"];
    [dic setObject:ApplicationDelegate.currentUserId forKey:@"userId"];
    
    AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
    requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [requestManager GET:@"http://ping.vsmu.cn/app/Interface/Comment?type=1002" parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject[@"MESSAGE_INFO"][@"CODE"] isEqualToString:@"0000"]) {
            NSMutableArray *arr = [[NSMutableArray alloc] init];
            //第一页
            if ([responseObject[@"PACKAGE_RSP"][@"PACKAGE"] isKindOfClass:[NSDictionary class]]) {
                [arr addObject:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
            }else{
                arr = [NSMutableArray arrayWithArray:responseObject[@"PACKAGE_RSP"][@"PACKAGE"]];
            }
            int x = startX;
            if (arr.count>0) {
                for (NSDictionary *dic in arr) {
                    CGRect r = CGRectMake(x, 6, 20, 20);
                    x = x+20+5;
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:r];
                    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
                    button.frame = r;
                    button.tag = [dic[@"LIKER"][@"ID"] integerValue];
                    [button addTarget:self action:@selector(buttonUserDetailAction:) forControlEvents:UIControlEventTouchUpInside];
                    imageView.layer.masksToBounds = YES;
                    imageView.layer.cornerRadius = 10; //设置图片圆角的尺度
                    [imageView setImageWithURL:[NSURL URLWithString:dic[@"LIKER"][@"HEAD_PIC_URL"]] placeholderImage:[UIImage imageNamed:@"nodata_userheader"]];
                    [self.productDetailHeaderView.scrollViewUsers addSubview:imageView];
                    [self.productDetailHeaderView.scrollViewUsers addSubview:button];
                }
            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:STR_MSG_NETWORK_ERROR];
    }];
}

- (void)buttonUserDetailAction:(UIButton*)button
{
    [QLPlayerManager openUserHomeWithId:(int)button.tag viewController:self];
}

- (void)initNavigation
{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.weChatNavigationBar=[[WeChatNavigationBar alloc] init];
    [self.view insertSubview:self.weChatNavigationBar belowSubview:self.viewGuide];
    self.weChatNavigationBar.titleLabel.text=@"";
    
  //  [self.weChatNavigationBar.leftButton setImage:[UIImage imageNamed:@"button_nav_back_a"] forState:UIControlStateNormal];
    [self.weChatNavigationBar.leftButton addTarget:self action:@selector(shouLeftVC) forControlEvents:UIControlEventTouchUpInside];
    
    [self.weChatNavigationBar.rightButton setImage:[UIImage imageNamed:@"seachBT"] forState:0];
    [self.weChatNavigationBar.rightButton addTarget:self action:@selector(search:) forControlEvents:UIControlEventTouchUpInside];
    self.weChatNavigationBar.rightButton.frame=CGRectMake(kUI_SCREEN_WIDTH-46, 30, 23, 23);
}

-(void)search:(id)btn{
    UIViewController * vc = [[TRSearchProductViewController alloc] init];
    //  self.hidesBottomBarWhenPushed = YES;
    //   self.tabBarController.tabBar.hidden =  YES;
  //  [self.navigationController pushViewController:vc animated:YES];
     [self presentViewController:vc animated:YES completion:nil];
}

- (void)setupDelete
{
    BOOL isMy = NO;
    NSDictionary *dic = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [dic ql_intForKey:@"ID"];
    if (uid==[self.productDetailHeaderView.userInfo ql_intForKey:@"ID"]) {
        isMy = YES;
    }
    if (isMy) {
        self.weChatNavigationBar.rightButton2.hidden = NO;
        self.weChatNavigationBar.rightButton2.height = 30;
        self.weChatNavigationBar.rightButton2.width = 25;
        self.weChatNavigationBar.rightButton2.center = self.weChatNavigationBar.center;
        self.weChatNavigationBar.rightButton2.top = 28;
//        self.weChatNavigationBar.rightButton2.left = self.weChatNavigationBar.rightButton2.left-30;
        [self.weChatNavigationBar.rightButton2 setImage:[UIImage imageNamed:@"删除"] forState:UIControlStateNormal];
        [self.weChatNavigationBar.rightButton2 addTarget:self action:@selector(delMyColl:)  forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void)delMyColl:(UIButton *)btn{
    UIActionSheet * actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"确定", nil];
    [actionSheet showInView:ApplicationDelegate.window];
}

-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    //确认
    if (buttonIndex==0) {
        [self deleteProduct];
    }
}

- (void)buttonCallMeAciton:(id)sender{
    [self.productDetailHeaderView buttonMakeCallAction:nil];
}

-(void)deleteProduct{
    
   // NSLog(@"%@",ApplicationDelegate.currentUserId);
    
    NSString *URLTmp = @"http://ping.vsmu.cn/app/Interface/Product?type=2006&userId=%@&ID=%@";
    URLTmp = [NSString stringWithFormat:URLTmp,ApplicationDelegate.currentUserId,self.productTypeId];
    NSString *URLTmp1 = [URLTmp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];  //转码成UTF-8  否则可能会出现错误
    URLTmp = URLTmp1;
   // NSLog(@"%@",URLTmp);
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString: URLTmp]];
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self dismissViewControllerAnimated:YES completion:nil];
        [SVProgressHUD showImage:nil status:@"成功"];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Failure: %@",error);
        [SVProgressHUD showImage:nil status:@"提交失败，请重试"];
    }];
    [operation start];
}

-(void)shareToWeixin:(UIButton *)bt
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = self.productDetailHeaderView.labelDesc.text;
    [SVProgressHUD showSuccessWithStatus:@"复制商品描述成功"];
    self.toWeixin = YES;
    [self downAll:bt];
}

//下载
-(void)downAll:(UIButton *)bt{
    
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = [self.productDetailHeaderView.info ql_stringForKey:@"DESCRIPTION"];
    if (self.productDetailHeaderView.imgs.count>0) {
        
        __block int countNum = 1;
        __block int downNum = 1;
        
        [MMProgressHUD showProgressWithStyle:MMProgressHUDProgressStyleRadial title:@"" status:@"相片保存中…" confirmationMessage:@"取消" cancelBlock:^{}];
        [ApplicationDelegate.webAPI getWebAPIWithParams:@{TYPE:SERVICE_CODE_PRODUCT_DOWNLOAD,PRODUCT_TYPE_ID:self.productTypeId} andMethodNode:NODE_PRODUCT completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
            
            if (state==1) {
                dispatch_queue_t queue = dispatch_queue_create("异步下载", nil);
                for (int n=0;n<[responseObject[@"PRODUCT_RSP"][@"PRODUCT"] count];n++) {
                    
                    NSDictionary * albumDict = responseObject[@"PRODUCT_RSP"][@"PRODUCT"][n];
                    
                    NSURL *url = [NSURL URLWithString:albumDict[@"PIC_URL"]];
                    //获取concurrent queue
                    //判断一下，当前图片是否需要异步
                    
                    //开多线程
                    dispatch_async(queue, ^(void) {
                        
                        NSData *resultData = [NSData dataWithContentsOfURL:url];
                        UIImage *img = [UIImage imageWithData:resultData];
                        
                        if (self.images==nil) {
                            self.images = [[NSMutableArray alloc] init];
                        }
                        NSString * message = [NSString stringWithFormat:@"第%d个文件下载失败",n];
                        if (img==nil) {
                            [MMProgressHUD dismiss];
                            MMProgressHUDShowSuccess(message);
                            return;
                        }
                        message =[NSString stringWithFormat:@"第%d个图片",downNum];
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            [MMProgressHUD updateProgress:(CGFloat)downNum/[responseObject[@"PRODUCT_RSP"][@"PRODUCT"] count] withStatus:message];
                        });
                        downNum++;
                        [self.images addObject:img];
                        if (self.images.count==[responseObject[@"PRODUCT_RSP"][@"PRODUCT"] count]) {
                            [self.library writeImages:self.images completion:^(id result) {
                                [MMProgressHUD dismiss];
                                dispatch_sync(dispatch_get_main_queue(), ^{
                                    [SVProgressHUD showImage:nil status:@"文字已复制，图片已下载，请上传"];
                                    //[self performSelector:@selector(openWeixin) withObject:nil afterDelay:2.0f];
                                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"图片已经下载完毕，文字已经复制，您可以上传至社交平台" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
                                    [alert show];
                                });
                            }];
                            
                        }
                    });
                }
                countNum++;
                
                [self downStatistics];
            }
            
        }];
    }
    
}

-(void)downStatistics
{
    NSDictionary * params;
    if ([NSString isBlankString:ApplicationDelegate.currentUserId]) {
        
        params=@{TYPE: @"1015",
                 @"ID" :self.productTypeId,
                 USERID:@"994"
                 };
    }else{
        params=@{TYPE: @"1015",
                 @"ID" :self.productTypeId,
                 USERID:ApplicationDelegate.currentUserId
                 };
    }
    
    [ApplicationDelegate.webAPI getWebAPIWithParams:params andMethodNode:NODE_DIRECTORY completed:^(NSInteger state, AFHTTPRequestOperation *operation, id responseObject) {
        if (state==1) {
            NSLog(@"下载统计成功");
        }
    }];
}

- (void)openWeixin
{
    if(self.toWeixin){
        self.toWeixin = NO;
        [WXApi openWXApp];
    }
}

-(void)shouLeftVC
{
    [self.navigationController popViewControllerAnimated:YES];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

//-(void)search:(id)btn{
//    UIViewController * vc = [[QLPlayerManager getStoryboard] instantiateViewControllerWithIdentifier:@"TRSearchProductViewController"];
//    [self.navigationController pushViewController:vc animated:YES];
//}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)removeTopButton{
    
}

-(void)visibleTop{
    
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    long count = self.contents==nil?0:self.contents.count;
   // return 5;
    return count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRCommentTableViewCell"];
    if (cell == nil) {
        cell = [[TRCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRCommentTableViewCell"];
    }
    NSDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    cell.viewController = self;
    [cell setNeedsDisplay];
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    TRCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TRCommentTableViewCell"];
    if (cell == nil) {
        cell = [[TRCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"TRCommentTableViewCell"];
    }
    NSDictionary *info = [self.contents objectAtIndex:indexPath.row];
    cell.info = info;
    return [cell getHeight];
}

#pragma mark - UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    NSDictionary *dic = [self.contents objectAtIndex:indexPath.row];
   
    DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:@"添加回复" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    UITextView *textView = [[UITextView alloc]init];
    //  textView.backgroundColor = [UIColor redColor];
    textView.frame = CGRectMake(0, 0, 250, 64);
    alertView.delegate = self;
    // self.alertView = alertView;
    NSLog(@"%@----------",alertView);
    NSLog(@"~~~~~~~~~~~······················");
    alertView.contentView = textView;
    [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
        //  NSLog(@"Tapped button '%@' at index: %ld", [alertView buttonTitleAtIndex:buttonIndex], (long)buttonIndex);
        if (buttonIndex == 1) {
            
            if (textView.text.length == 0) {
                return ;
            }
            
            NSString *userId = [NSStandardUserDefaults objectForKey:@"USER_ID"];
            NSDictionary *parameters = @{@"userId" : userId,
                                         @"type" : @"10003",
                                         @"commentId" : [NSString stringWithFormat:@"%zd",[dic ql_intForKey:@"ID"]],
                                         @"productId":dic[@"PRODUCT_ID"],
                                         @"content" : textView.text
                                         };
            //   NSLog(@"-------------%@",parameters);
            AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
            requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
            [SVProgressHUD show];
            //int productId = [self.info ql_intForKey:@"ID"];
            [requestManager POST:@"http://ping.vsmu.cn/app/Interface/Comment" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
                NSDictionary *dic = responseObject;
                if ([dic ql_intForKey:@"code"]==0000) {
                    [SVProgressHUD showSuccessWithStatus:@"评论发表成功"];
                }
                //    [self loadData:1];
           //     [[NSNotificationCenter defaultCenter]postNotificationName:@"kReplyAction" object:nil userInfo:nil];
                [self loadData:1];
                [alertView removeFromSuperview];
                //  self.alertView = nil;
                
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                [SVProgressHUD showErrorWithStatus:@"评论发表失败"];
                
                // self.alertView = nil;
                [alertView removeFromSuperview];
            }];
        }
        
    }];

    self.textFieldContent.placeholder = [NSString stringWithFormat:@"回复:%@",dic[@"AUTHOR_NAME"]];
    self.commentId = [dic ql_intForKey:@"ID"];
    [self.textFieldContent becomeFirstResponder];
}

- (void)addFooter
{
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    refreshFooterView = footer;
    footer.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
      //  [self loadComments:self.nextPage];
        [self loadData:self.nextPage];
    };
    [self performSelector:@selector(loadFirstData) withObject:nil afterDelay:0.2];
}
- (void)loadFirstData
{
    [refreshHeaderView beginRefreshing];
}
- (void)addHeader
{
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    refreshHeaderView = header;
    header.beginRefreshingBlock = ^(MJRefreshBaseView *refreshView) {
        [self loadProductDetail];
        [self loadData:1];
    };
    [self performSelector:@selector(loadFirstData) withObject:nil afterDelay:0.2];
}

- (IBAction)buttonFavAction:(id)sender
{
//    self.favBtn.selected = !self.favBtn.selected;
//    if (self.favBtn.isSelected) {
//        [self.favBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-(s)"] forState:UIControlStateNormal];
//    } else {
//        [self.favBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-(3)"] forState:UIControlStateNormal];
//    }
    
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [userInfo ql_intForKey:@"ID"];
    int productId = (int)[self.productTypeId integerValue];
    
    BOOL b = [[QLFavoriteManager shareInstance] isFavoriteWithUserId:uid productId:productId];
    if (b) {
        [[QLFavoriteManager shareInstance] deleteFavoriteWithUserId:uid productId:productId callback:^(BOOL isCache, id data) {
            [self updateFavButton];
            
        }];
    }else{
        [[QLFavoriteManager shareInstance] addFavoriteWithUserId:uid productId:productId callback:^(BOOL isCache, id data) {
            [self updateFavButton];
            
        }];
    }
}


- (void)doneWithView:(id)sender
{
 //   self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    [refreshFooterView endRefreshing];
    [refreshHeaderView endRefreshing];
    
  //  self.tableView.contentInset = UIEdgeInsetsMake(0, 0, 37, 0);
    // 刷新表格
    [self.tableView reloadData];
    
   
    
}

#pragma mark - QLMaskNodataViewOnClickDelegate
-(void)onClick:(id)sender
{
    [QLMaskUtil hideNodataMaskWithView:self.tableView];
    [refreshHeaderView beginRefreshing];
}

- (IBAction)buttonShareAction:(id)sender
{
    NSString *imgUrl = [self.info ql_stringForKey:@"THUMBNAIL_URL"];
    imgUrl = [imgUrl stringByReplacingOccurrencesOfString:@"_smaller" withString:@""];
    UIImageView *img=[[UIImageView alloc]init];
     [img setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@"nodata_publics"]];
    ApplicationDelegate.shareContent=self.info[@"DESCRIPTION"];
    ApplicationDelegate.shareTitle=self.info[@"NAME"];
    ApplicationDelegate.shareURL=self.info[@"SHARE_URL"];
    ApplicationDelegate.shareImage = img.image;
    //bei 分享
    NSArray*shareButtonTitleArray = @[@"微信",@"微信朋友圈",@"QQ",@"新浪微博",@"QQ空间",@"复制"];
    NSArray * shareButtonImageNameArray= @[@"sns_icon_22",@"sns_icon_23",@"sns_icon_40",@"sns_icon_1",@"QQkj",@"fuzhi"];
    
    self.lxActivity = [[LXActivity alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" ShareButtonTitles:shareButtonTitleArray withShareButtonImagesName:shareButtonImageNameArray];
    [self.lxActivity showInView:ApplicationDelegate.window];
    [ApplicationDelegate.window insertSubview:self.lxActivity aboveSubview:self.weixinView];
}

#pragma mark ----分享视图代理
- (void)didClickOnImageIndex:(NSInteger )imageIndex
{
    switch (imageIndex) {
        case 0:
            [ApplicationDelegate changeScene:0];
            [ApplicationDelegate sendLinkContent];
            break;
        case 1:
            [ApplicationDelegate changeScene:1];
            [ApplicationDelegate sendLinkContent];
            break;
        case 2: //QQ分享
            
            [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:ApplicationDelegate.shareURL];
            
            [self yixunshare:UMShareToQQ];
            
            break;
        case 3: //新浪微博
            
            
            [self yixunshare:UMShareToSina];
            break;
        case 4://QQ空间
            
            [UMSocialQQHandler setQQWithAppId:QQWithAppId appKey:QQWithAppKey url:ApplicationDelegate.shareURL];
            
            
            [self yixunshare:UMShareToQzone];
            break;
        case 5:
        {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string =[NSString stringWithFormat:@"%@\n%@",ApplicationDelegate.shareContent,ApplicationDelegate.shareURL];
            [SVProgressHUD showErrorWithStatus:@"网址已经复制，您可以直接发送给好友"];
        }break;
//        case 6:
//            //设置易信Appkey和分享url地址
//            [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:ApplicationDelegate.shareURL];
//            [self yixunshare:UMShareToYXSession];
//            break;
//        case 7:
//            //设置易信Appkey和分享url地址
//            [UMSocialYixinHandler setYixinAppKey:YiXunWithAppId url:ApplicationDelegate.shareURL];
//            [self yixunshare:UMShareToYXTimeline];
//            break;
            
        default:
            break;
    }
}

-(void)yixunshare:(NSString *)pingtai
{
    NSString *shareText = ApplicationDelegate.shareContent;
    UIImage *shareImage = ApplicationDelegate.shareImage;
    
    if ([pingtai isEqualToString:UMShareToSina]) {
        shareText = [NSString stringWithFormat:@"%@%@",ApplicationDelegate.shareContent,ApplicationDelegate.shareURL];
        shareImage=ApplicationDelegate.shareImageHD;
    }
    UMSocialUrlResource *UMUrl=[[UMSocialUrlResource alloc] initWithSnsResourceType:UMSocialUrlResourceTypeDefault url:ApplicationDelegate.shareURL];
    
    [[UMSocialDataService defaultDataService] postSNSWithTypes:@[pingtai] content:shareText image:shareImage location:nil urlResource:UMUrl presentedController:self completion:^(UMSocialResponseEntity * response){
        if (response.responseCode == UMSResponseCodeSuccess) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:@"分享成功" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        } else if(response.responseCode != UMSResponseCodeCancel) {
            UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"失败" message:@"分享失败" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
            [alertView show];
        }
    }];
}

#pragma mark --UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    return YES;
}

- (void)showHint:(NSString *)hint {
    if ([hint isEqualToString:@"录音没有开始"]) {
        NSLog(@"dd");
    }
    
    //显示提示信息
    UIView *view = [[UIApplication sharedApplication].delegate window];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.userInteractionEnabled = NO;
    // Configure for text only and offset down
    hud.mode = MBProgressHUDModeText;
    hud.labelText = hint;
    hud.margin = 10.f;
    hud.yOffset = 150.f;
    hud.removeFromSuperViewOnHide = YES;
    [hud hide:YES afterDelay:2];
}

- (void)updateFavButton
{
    NSDictionary *userInfo = [[QLUserManager shareInstance] getLastUserInfoFromNative];
    int uid = [userInfo ql_intForKey:@"ID"];
    int productId = (int)[self.productTypeId integerValue];
    
    BOOL b = [[QLFavoriteManager shareInstance] isFavoriteWithUserId:uid productId:productId];
    if (b) {
        [self.favBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-(s)"] forState:UIControlStateNormal];
      //  [self.imageViewFav setImage:[UIImage imageNamed:@"iconfont-shoucang-(s)"]];
    }else{
        [self.favBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-shoucang-(3)"] forState:UIControlStateNormal];
      //  [self.imageViewFav setImage:[UIImage imageNamed:@"iconfont-shoucang-(3)"]];
    }
}

- (IBAction)buttonConnectSheAction:(id)sender
{
    if (self.productDetailHeaderView.userInfo) {
        [self.productDetailHeaderView buttonConnectSheAction:sender];
    }
}

- (IBAction)buttonPlayAction:(id)sender
{
    NSString *url = [self.productInfo ql_stringForKey:@"TONE_URL"];
    [[QLRecordPlayer shareInstance] play:[NSURL URLWithString:url]];
}

- (IBAction)buttonAddCarAction:(id)sender {
    
    DLAVAlertView *alertView = [[DLAVAlertView alloc] initWithTitle:@"添加评论" message:nil delegate:nil cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    UITextView *textView = [[UITextView alloc]init];
  //  textView.backgroundColor = [UIColor redColor];
    textView.frame = CGRectMake(0, 0, 250, 64);
    alertView.contentView = textView;
    [alertView showWithCompletion:^(DLAVAlertView *alertView, NSInteger buttonIndex) {
        NSLog(@"Tapped button '%@' at index: %ld", [alertView buttonTitleAtIndex:buttonIndex], (long)buttonIndex);
        if (buttonIndex == 1) {
            
          NSString *userId = [NSStandardUserDefaults objectForKey:@"USER_ID"];
          NSDictionary *parameters = @{@"userId" : userId,
                                       @"type" : @"10003",
                                       @"productId":self.productTypeId,
                                       @"content" : textView.text
                                       };

          AFHTTPRequestOperationManager *requestManager = [AFHTTPRequestOperationManager manager];
          requestManager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
          [SVProgressHUD show];
          //int productId = [self.info ql_intForKey:@"ID"];
          [requestManager POST:@"http://ping.vsmu.cn/app/Interface/Comment" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
              NSDictionary *dic = responseObject;
              if ([dic ql_intForKey:@"code"]==0000) {
                  [SVProgressHUD showSuccessWithStatus:@"评论发表成功"];
              }
              [self loadData:1];
          } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
              [SVProgressHUD showErrorWithStatus:@"评论发表失败"];
          }];
        }
        
    }];
}

- (IBAction)buttonBuyNowAction:(id)sender {
    
    NSDictionary *dic=[[NSDictionary alloc]init];
    dic=self.productDetailHeaderView.userInfo;
    NSLog(@"dic==%@",dic);
    NSString *name=[dic objectForKey:@"NAME"];
    if ([[self.productDetailHeaderView.userInfo allKeys] containsObject:@"PHONE"]) {
        NSString *tel = self.productDetailHeaderView.userInfo[@"PHONE"];
        NSString *telStr = [NSString stringWithFormat:@"tel://%@",tel];
        NSURL *telUrl = [NSURL URLWithString:telStr];
        [self.webView loadRequest:[NSURLRequest requestWithURL:telUrl]];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"对不起对方未绑定手机号码，请先去填写 " delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];//bei 1125
        [alert show];
    }
  
}


#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {
      //  [alertView removeFromSuperview];
        return;
    }
    
    if (alertView.tag==2) {
        
        if (buttonIndex==1) {
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            NSString *wechat = [self.productDetailHeaderView.userInfo ql_stringForKey:@"WECHAT"];
            pasteboard.string = wechat;
            [self openWeixin];
        }
    }
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset
{
    //TRFindViewController *fvc = (TRFindViewController*)self.viewController;
    if (historyY+150<targetContentOffset->y)
    {
        [self fullScreen];
    }
    else if(historyY-150>targetContentOffset->y)
    {
        [self fullScreenExit];
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    historyY = scrollView.contentOffset.y;
}

- (void)fullScreen
{

    self.weChatNavigationBar.hidden = YES;
   // self.view.backgroundColor = [UIColor greenColor];
  //  self.view.opaque = YES;
    CGRect fullFrame = [UIApplication sharedApplication].keyWindow.bounds;
//    self.view.backgroundColor = [UIColor redColor];
//    self.view.frame = fullFrame;
  //  self.navigationController.navigationBar.hidden = YES;
    //  self.weChatNavigationBar.opaque = NO;
    //self.weChatNavigationBar.hidden = YES;
 //   self.tableView.frame = fullFrame;
  //  self.tableView.contentInset = UIEdgeInsetsMake(20, 0, 0, 0);
    self.tableView.frame = fullFrame;

}

- (void)fullScreenExit
{
    self.weChatNavigationBar.hidden = NO;
    self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.weChatNavigationBar.frame), self.view.width, self.view.height);
   // self.tableView.contentInset = UIEdgeInsetsMake(64, 0, 37, 0);
}


@end
